package com.zoweunion.mechanic.service.base.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.FacilitatorPersonnelRelationDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.dao.base.EngineLockCarDao;
import com.zoweunion.mechanic.dao.base.LockCarMapper;
import com.zoweunion.mechanic.dao.base.OwnerDao;
import com.zoweunion.mechanic.plugins.jpush.JiguangPush;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.service.base.EngineLockCarService;
import com.zoweunion.mechanic.util.Orgin;
import com.zoweunion.mechanic.util.SmsUtil;
import com.zoweunion.mechanic.util.UuidUtil;
import com.zoweunion.mechanic.util.constants.PushConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EngineLockCarServiceImpl  extends BaseService implements EngineLockCarService {

    @Autowired
    private EngineLockCarDao engineLockCarDao;
    @Autowired
    private FacilitatorPersonnelRelationDao facilitatorPersonnelRelationDao;
    @Autowired
    private JiguangPush jiguangPush;
    @Autowired
    LockCarMapper lockCarMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    OwnerDao ownerDao;
    @Autowired
    OrderDao orderDao;


    /**
     *服务商按省分组
     *
     */
    @Override
    public Map<Integer, List<Map<String, Object>>> getServerByProvinceMap(Map<String, Object> reqMap) {
        String sIds = Orgin.getString(reqMap, "sId");
        String userId = Orgin.getString(reqMap, "userId");
        List<String> strings = this.getServer(sIds,userId);
        String serverString = "'" + StringUtils.join(strings, "','") + "'";
        List<Map<String, Object>> serverInfo =
                facilitatorPersonnelRelationDao.selectServerInfo(serverString);
        Map<Integer, List<Map<String, Object>>> serverByProvinceMap = serverInfo.stream()
                .collect(Collectors.groupingBy(i -> Orgin.getInteger(i, "province_code")));
        return serverByProvinceMap;
    }

    /**
     * 车主列表展示 ((分页,条件查询)
     * @param reqMap 分页条件 查询条件(车主姓名,电话)
     * @return 车主信息 包含已拥有车辆数
     */
    @Override
    public PageInfo<Map<String, Object>> getPageQuery(Map<String, Object> reqMap) {
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> resultList = engineLockCarDao.getCarsOwner(reqMap);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<Map<String, Object>>(resultList);
        return mapPageInfo;
    }

    /**
     * 服务商被锁车计数
     *
     * @return
     */
    @Override
    public Integer getLockCarCount(Map<String, Object> reqMap) {
        Integer lockCarCount = engineLockCarDao.getLockCarCount(reqMap);
        return lockCarCount;
    }

    /**
     * 服务商车辆计数
     *
     * @return
     */
    @Override
    public Integer getEngineCarCount(Map<String, Object> reqMap) {
        Integer engineCarCount = engineLockCarDao.getEngineCarCount(reqMap);
        return engineCarCount;
    }

    /**
     * 车辆命令插入
     *
     * @return
     */
    @Override
    public void thingsIdCarOperation(Map<String, Object> reqMap) {
        Integer lockCar = engineLockCarDao.getThingsIdCarOperation(reqMap);
        if (lockCar != 0){
            engineLockCarDao.updateThingsIdCarOperation(reqMap);
        }
        if (!reqMap.containsKey("lock_speed")) {
            reqMap.put("lock_speed", "");
        }
        if (!reqMap.containsKey("lock_torque")) {
            reqMap.put("lock_torque", "");
        }
        try {
            //存储redis远程升级指令
            this.handleMessage(reqMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int lockType = Orgin.getIntValue(reqMap, "lock_type");
        reqMap.put("id", UuidUtil.get32UUID());
        engineLockCarDao.thingsIdCarOperation(reqMap);
        engineLockCarDao.updateCarIsLoeckByCarId(Orgin.getString(reqMap, "car_id"), Orgin.getString(reqMap, "isLocked"));
        if (Orgin.getIntValue(reqMap, "smsStatus") == 1) {
            // hasLockCar   状态值 0-没有锁车功能 1-普通锁车 2-继电器锁车
            String hasLockCar = lockCarMapper.getHasLockCar(Orgin.getString(reqMap, "car_id"));
            if ("1".equals(hasLockCar)) {
                if (lockType == 1) {
                    // 限速提醒
                    this.sendMessageWarningLimitSpeed(reqMap);
                } else if (lockType == 2) {
                    // 锁车
                    this.sendMessageWarningLockCar(reqMap);
                    // 解锁
                } else if (lockType == 3) {
                    this.sendMessageWarningUnlockCar(reqMap);
                }
            } else if ("2".equals(hasLockCar)) {
                if (lockType == 4) {
                    // 锁车
                    this.sendMessageWarningLockCar(reqMap);
                } else if (lockType == 5) {
                    // 解锁
                    this.sendMessageWarningUnlockCar(reqMap);
                }
            }
        }
    }

    public void handleMessage(Map<String, Object> reqMap){
        String thingsId = Orgin.getString(reqMap, "things_id");
        lockCarMapper.updateMessageError(thingsId);
        List<Map<String, Object>> newlockcar = redisUtil.getList("newlockcar");
        List<Map<String, Object>> things_id = newlockcar.stream().filter(i -> !i.get("things_id").toString().equals(thingsId))
                .collect(Collectors.toList());

        if (redisUtil.exists("newlockcar") && things_id.size() > 0) {
            redisUtil.remove("newlockcar");
        }

        redisUtil.insertList(things_id,"newlockcar");
        //删除之前redis指令
        int lockType = Orgin.getIntValue(reqMap, "lock_type");
        int lockSpeed = Orgin.getIntValue(reqMap, "lock_speed");
        int lockTorque = Orgin.getIntValue(reqMap, "lock_torque");
        //插入指令消息
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMddHHmm");
        String nowDateString = formatDate.format(new Date());
        String s = Integer.toHexString(Integer.parseInt(nowDateString.substring(2, 4)));
        String s1 = Integer.toHexString(Integer.parseInt(nowDateString.substring(4, 6)));
        String s2 = Integer.toHexString(Integer.parseInt(nowDateString.substring(6, 8)));
        String s3 = Integer.toHexString(Integer.parseInt(nowDateString.substring(8, 10)));
        String s4 = Integer.toHexString(Integer.parseInt(nowDateString.substring(10, 12)));
        String date=addZero(s)+addZero(s1)+addZero(s2)+addZero(s3)+addZero(s4);
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("things_id", thingsId);

        //操作编号-1限速，2命令锁车，3命令解锁，4继电器锁车，5继电器解锁
        if(lockType == 1) {
            String slockSpeed = String.format("%02x", lockSpeed);
            if (slockSpeed.length()==3){
                slockSpeed="0"+slockSpeed;
            }
            if (slockSpeed.length()==1){
                slockSpeed="0000";
            }
//4021000A3131
// 03e8
// 3216
// 07041135
            String slockTorque = Integer.toHexString(lockTorque);
            addZero(Integer.toHexString(lockTorque));
            //数据域存入redis
            String message="4021000A3131"+slockSpeed+slockTorque+date;
            hashMap.put("message",message);
            redisUtil.lSet("newlockcar",hashMap);

        }else if(lockType == 2 || lockType == 4){

            //数据域存入redis
            String message="4021000A31320000000000000000";
            hashMap.put("message",message);
            redisUtil.lSet("newlockcar",hashMap);
        }else if(lockType == 3 || lockType == 5) {

            hashMap.put("message", "4021000A32000000000000000000");
            redisUtil.lSet("newlockcar", hashMap);
        }
    }


    private String addZero(String message){
        if (message.length()==1){
            message="0"+message ;
        }
        return message;
    }

    /**
     * 发送普通限速及时消息
     * @param
     */
    private void sendMessageWarningLimitSpeed(Map<String, Object> reqMap) {
        List<Map<String, Object>> carMapList = lockCarMapper.getLockCarThingsByCarId(Orgin.getString(reqMap, "car_id"));
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();

            String content = String.format(SmsUtil.WarningLimitSpeed, carType, model, brand);
            // 发送消息
            this.sendMessage(carMapList, content, content);
        }
    }

    /**
     * 发送锁车及时消息
     * @param
     */
    private void sendMessageWarningLockCar(Map<String, Object> reqMap) {
        List<Map<String, Object>> carMapList = lockCarMapper.getLockCarThingsByCarId(Orgin.getString(reqMap, "car_id"));
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();

            String content = String.format(SmsUtil.WarningLockCar, carType, model, brand);
            // 发送消息
            this.sendMessage(carMapList, content, content);
        }
    }

    /**
     * 发送解锁及时消息
     * @param
     */
    private void sendMessageWarningUnlockCar(Map<String, Object> reqMap) {
        List<Map<String, Object>> carMapList = lockCarMapper.getLockCarThingsByCarId(Orgin.getString(reqMap, "car_id"));
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();

            String content = String.format(SmsUtil.WarningUnlockCar, carType, model, brand);
            // 发送消息
            this.sendMessage(carMapList, content, content);
        }
    }

    /**
     * 车主名下车辆列表展示
     * @param reqMap 分页条件 查询条件(车主姓名,电话，物联编号，制造编号)
     * @return 车主信息
     */
    @Override
    public List<Map<String, Object>> carListByOwner(Map<String, Object> reqMap) {
        List<Map<String, Object>> resultList = engineLockCarDao.carListByOwner(reqMap);
        return resultList;
    }

    @Override
    public Integer lockCarCountEngine(Map<String, Object> reqMap) {
        Integer lockCarCountEngine = engineLockCarDao.lockCarCountEngine(reqMap);
        return lockCarCountEngine;
    }

    @Override
    public Integer carCountEngine(Map<String, Object> reqMap) {
        Integer carCountEngine = engineLockCarDao.carCountEngine(reqMap);
        return carCountEngine;
    }

    //根据主机厂获取子服务商sid
    private List<String> getServer(String sId, String userId) {
        String role = engineLockCarDao.getRoleByUserId(userId);
        if (role.equals("7")) {
            return facilitatorPersonnelRelationDao.selectCountBySid(sId);
        } else {
            List<String> sIdList = engineLockCarDao.getSIdByUserId(userId);
            return sIdList;
        }
    }

    /**
     * 消息推送
     * @param  carMapList
     * @param  content
     * @param  contentPush
     */
    private void sendMessage(List<Map<String, Object>> carMapList, String content, String contentPush){
        if (org.apache.commons.lang.StringUtils.isBlank(contentPush)) {
            contentPush = content;
        }
        Set<String> oMobilePhonelist = new HashSet<>();
        Set<String> oIdlist = new HashSet<>();
        Set<String> dMobilePhonelist = new HashSet<>();
        Set<String> dIdlist = new HashSet<>();
        for (Map<String, Object> carMap : carMapList) {
            if (carMap.get("o_mobile_phone") != null) {
                oMobilePhonelist.add(carMap.get("o_mobile_phone").toString());
            }
            if (carMap.get("o_id") != null) {
                oIdlist.add(carMap.get("o_id").toString());
            }
            if (carMap.get("d_mobile_phone") != null) {
                dMobilePhonelist.add(carMap.get("d_mobile_phone").toString());
            }
            if (carMap.get("d_id") != null) {
                dIdlist.add(carMap.get("d_id").toString());
            }
        }
        // 给车主发送 短信和app消息推送
        oMobilePhonelist.forEach(oMobilePhone -> SmsUtil.sendSms(oMobilePhone, content));
        String finalContentPush = contentPush;
        oIdlist.forEach(oId -> jiguangPush.jiguangPush(oId, finalContentPush, PushConstants.KEY_JUMP_URL,"/car"));
        // 给司机发送
        dMobilePhonelist.forEach(dMobilePhone -> SmsUtil.sendSms(dMobilePhone, content));
        String finalContentPush1 = contentPush;
        dIdlist.forEach(dId -> jiguangPush.jiguangPush(dId, finalContentPush1, PushConstants.KEY_JUMP_URL,"/car"));
    }

    /**
     * 车辆锁车次数
     *
     * */
    private Integer lockCount(Map<String, Object> reqMap) {
        Integer lockCount = 0;
        lockCount = engineLockCarDao.lockCount(reqMap);
        return lockCount;
    }

}
